<template>
	<el-drawer v-model="drawer" :with-header="false" @close="close" :append-to-body="true" :size="size" ref="drawerRef"
		class="customer-detail-drawer" :modal="true" modal-class="customer-modal">

		<div class="page-container">
			<el-form :model="form" :rules="rules" size="small" label-width="150px" ref="ruleRefForm" class="refForm">
				<el-form-item label="发布内容:" prop="articleType">
					<el-radio-group v-model="form.articleType">
						<el-radio :label="0">文章</el-radio>
						<el-radio :label="1">视频</el-radio>
					</el-radio-group>
				</el-form-item>
				<el-form-item label="标题:" prop="title">
					<el-input v-model="form.title" style="width: 500px" placeholder="请输入标题"></el-input>
				</el-form-item>
				<el-form-item label="作者:">
					<el-input v-model="form.author" placeholder="请输入作者名称" style="width: 500px"></el-input>
				</el-form-item>
				<el-form-item :label="form.articleType=='0'?'文章封面:':'上传视频'" prop="image">
					<el-upload :file-list="form.backageImage" ref="uploadBanner" :action="uploadUrl" :headers="headers"
						list-type="picture-card" :auto-upload="true" :multiple="false" :limit="form.articleType=='0'?3:1"
						:on-success="backageImagesOnSuccess">
						<el-icon>
							<ele-Camera />
						</el-icon>
						<template #file="{ file }">
							<video class="el-upload-list__item-thumbnail" v-if="form.articleType=='1'" :src="file.url"></video>
							<img class="el-upload-list__item-thumbnail" v-if="form.articleType=='0'" :src="file.url" />
							<span class="el-upload-list__item-actions">
								<span class="el-upload-list__item-preview" @click="handlePictureCardPreview(file)">
									<el-icon>
										<ele-ZoomIn />
									</el-icon>
								</span>
								<span class="el-upload-list__item-delete" @click="handleRemove(2, file)">
									<el-icon>
										<ele-Delete />
									</el-icon>
								</span>
							</span>
						</template>
					</el-upload>
				</el-form-item>
				<el-form-item label="摘要:" prop="articleAbstract" v-if="form.articleType=='0'">
					<el-input v-model="form.articleAbstract" style="width: 500px" type="textarea" />
				</el-form-item>
				<el-form-item label="发布时间:">
					<el-date-picker v-model="form.createTime" type="datetime" placeholder="请选择"
						:default-time="defaultTime" :default-value="defaultTime" value-format="YYYY-MM-DD HH:mm:ss" />
				</el-form-item>
				<el-form-item label="请关联商品" v-if="form.articleType=='0'">
					<el-tag class="spec-tag" v-for="(item, index) in form.articleSkuRelations"
						:key="item.skuId" closable size="small" style="margin-right:10px;height: 25px;" effect="light"
						@close="delSpu(index)">{{ item.skuName }}</el-tag>
					<el-button type="primary" @click="selectShopList">关联商品</el-button>
				</el-form-item>

				<el-form-item label="状态:" prop="status">
					<el-radio-group v-model="form.status">
						<el-radio :label="0">暂不发布</el-radio>
						<el-radio :label="1">发布</el-radio>
					</el-radio-group>
				</el-form-item>

				<el-form-item label="标签">
					<el-tag v-for="(tag,index) in form.articleTags" :key="tag.id" style="margin-right: 5px;" closable
						:disable-transitions="false" @close="handleCloseTags(tag)">
						{{ tag.tagName }}
					</el-tag>
					<el-input v-if="inputVisible" v-model="inputValue" style="width: 120px" size="small"
						@keyup.enter="handleInputConfirm" @blur="handleInputConfirm" />
					<el-button v-else class="button-new-tag ml-1" size="small" @click="showInput(index)">
						+ 添加标签
					</el-button>
				</el-form-item>

				<el-form-item label="分类">
					<el-select v-model="form.classId" placeholder="请选择分类">
						<el-option v-for="item in classOptions" :key="item.id" :label="item.className"
							:value="item.id" />
					</el-select>
					<el-button style="margin-left: 10px;" type="primary" @click="openShowClass">
						<!-- <i class="fa fa-plus" aria-hidden="true"></i> -->
						管理分类
					</el-button>
				</el-form-item>
				<el-form-item label="收录类型" prop="collectionTypeId">
					<el-select v-model="form.collectionTypeId" placeholder="请选择收录类型">
						<el-option v-for="item in collectionTypeOptions" :key="item.id" :label="item.collectionName"
							:value="item.id" />
					</el-select>
				</el-form-item>

				<el-form-item label="内容" v-if="form.articleType=='0'">
					<Editor v-model="form.content" />
				</el-form-item>
			</el-form>
		</div>
		<template #footer>
			<span class="dialog-footer">
				<el-button type="primary" size="small" @click="submitForm(ruleRefForm)">保存</el-button>
				<el-button size="small" @click="close">取消</el-button>
			</span>
		</template>

		<el-dialog v-model="dialogBannerVisible" title="图片预览">
			<img w-full :src="dialogImageUrl" alt="图片预览" style="display:block;margin: 0 auto;width:100%" />
		</el-dialog>

		<!-- 添加分类 -->
		<article-class-detail-form v-model:dialogDrawer="dialogArticleClassFormVisible"
			v-model:classOptions="classOptions" @emitClass="emitClass"></article-class-detail-form>
		<!-- 选择商品 -->
		<select-shop v-model:dialogDrawer="dialogShopVisible" title="关联商品" :is-batch="true"
			@onSelectSubmit="selectShopSubmit"></select-shop>

		<div class="tabs-list">
			<div class="close-btn" @click="close">
				<el-icon color="var(--next-color-white)" size="28px">
					<ele-CircleClose />
				</el-icon>
			</div>
		</div>
	</el-drawer>
</template>

<script>
	import {
		toRefs,
		computed,
		reactive,
		watch,
		onMounted,
		ref,
		nextTick
	} from 'vue'
	import {
		ElMessage,
		ElMessageBox,
		ElInput
	} from 'element-plus'
	import {
		create,
		update
	} from '/@/api/ws/article'
	import Editor from '/@/components/editor/index.vue'
	import {
		Session
	} from '/@/utils/storage'
	import ArticleClassDetailForm from './ArticleClassDetailForm.vue'
	import {
		getAllList,
		getCollectionList
	} from '/@/api/ws/articleClass'
	import SelectShop from '../../components/SelectShop.vue'
	export default {
		name: 'DetailForm',
		components: {
			Editor,
			ArticleClassDetailForm,
			SelectShop
		},
		props: {
			dialogDrawer: {
				type: Boolean,
				default: false
			},
			defaultForm: {
				type: Object,
				default () {
					return {}
				}
			}
		},
		setup(props, context) {
			const {
				defaultForm
			} = toRefs(props)

			const uploadBanner = ref()
			const state = reactive({
				uploadUrl: '/api/file/filaAttach/upload',
				headers: {
					'17work': Session.get('token')
				},
				dialogImageUrl: null,
				dialogBannerVisible: false,
				rules: {
					title: [{
						required: true,
						message: '请输入标题',
						trigger: 'blur'
					}],
					collectionTypeId: [{
						required: true,
						message: '请选择收录类型',
						trigger: 'change'
					}],
					articleType: [{
						required: true,
						message: '请选择发布类型',
						trigger: 'change'
					}],
				},
				dialogArticleClassFormVisible: false,
				classOptions: [],
				collectionTypeOptions: [],
				//标签
				dynamicTags: ['Tag 1', 'Tag 2', 'Tag 3'],
				inputVisible: false,
				inputValue: '',
				dialogShopVisible: false
			})
			const defaultTime = new Date()
			let form = computed({
				get: () => defaultForm.value,
				set: val => {
					context.emit('update:defaultForm', val)
				}
			})
			const {
				dialogDrawer,
				ruleRefForm
			} = toRefs(props)
			let drawer = computed({
				get: () => dialogDrawer.value,
				set: (val) => {
					context.emit('update:dialogDrawer', val)
				}
			})
			watch(() => dialogDrawer.value, val => {
				context.emit("update:dialogDrawer", val)
				if (val) {
					getArticleClassList()
					nextTick(() => {

						if (document.querySelector('.el-drawer__body')) {
							document.querySelector('.el-drawer__body').onscroll = e => {
								state.scrollTop = e.target.scrollTop
							}
						}
						if (document.querySelector('.refLine')) {
							state.refLineTop = document.querySelector('.refLine').offsetTop
						}
					})
				}
			})
			const getSize = () => {
				if (document.body.clientWidth <= 1400) {
					return '1220px'
				} else {
					return '85%'
				}
			}

			state.size = getSize()
			const close = () => {
				context.emit("update:dialogDrawer", false)
			}

			const submitForm = async (formEl) => {
				if (!formEl) return
				await formEl.validate((valid) => {
					if (valid) {
						let data = form.value
						if (data.backageImage.length > 0) {
							let images = []
							 for(let i of data.backageImage){
								 images.push(i.url)
							 }
							data.image = images.join(",")
						}else{
							data.image = null
						}
						if (data.id != null && data.id != '') {
							update(data).then(res => {
								if (res.code == 0) {
									ElMessage.success("修改成功");
									context.emit('onDetailSubmit', true)
								} else {
									ElMessage.error("修改失败");
								}
							})
						}
						// 新增
						else {
							create(data).then(res => {
								if (res.code == 0) {
									ElMessage.success("添加成功");
									context.emit('onDetailSubmit', true)
								} else {
									ElMessage.error("添加失败");
								}
							})

						}
					}
				})

			}
			const handlePictureCardPreview = (file) => {
				state.dialogImageUrl = file.url
				state.dialogBannerVisible = true
			}
			const handleRemove = (val, file) => {
				uploadBanner.value.handleRemove(file)
			}
			const backageImagesOnSuccess = (response, uploadFiles) => {
				let data = form.value.backageImage
				data.forEach((e, index) => {
					if(e.name == 'images'){
						data[index] = e
					}else{
						try {
							data[index] = {
								name: e.response.data.name,
								src: e.response.data.src,
								url: e.response.data.src
							}
						} catch(err) {
							data[index] = {
								name: e.name,
								src: e.src,
								url: e.src
							}
						}
				  	}
				})
				form.value.backageImage = data
			}
			const openShowClass = () => {
				state.dialogArticleClassFormVisible = true
			}
			const onArticleClassSubmit = (row) => {

			}
			const getArticleClassList = () => {
				getAllList().then(res => {
					if (res.code == 0) {
						state.classOptions = res.data
					}
				})
				getCollectionList().then(res => {
					state.collectionTypeOptions = res.data
				})
			}
			const emitClass = () => {
				console.log(state.classOptions)
			}
			const showInput = (val) => {
				state.inputVisible = true
				document.getElementById(form.value.articleTags[val])?.focus()
				// nextTick(() => {
				//     InputRef.value!.input!.focus()
				//   })
			}

			const handleInputConfirm = () => {
				console.log(state.inputValue)
				if (state.inputValue) {
					form.value.articleTags.push({id:'',tagName:state.inputValue})
				}
				state.inputVisible = false
				state.inputValue = ''
			}
			const handleCloseTags = (tag) => {
				form.value.articleTags.splice(form.value.articleTags.indexOf(tag), 1)
			}

			// 关联商品
			const selectShopList = () => {
				state.dialogShopVisible = true
			}
			const selectShopSubmit = (data) => {
				let v = []
				for (let d of data) {
					v.push({
						skuId: d.skuInfos[0].skuId,
						skuName: d.skuInfos[0].skuName
					})
				}
				state.dialogShopVisible = false
				form.value.articleSkuRelations = v
			}
			//移除商品
			const delSpu = (index) => {
				form.value.articleSkuRelations.splice(index, 1)
			}

			onMounted(() => {

			})
			return {
				drawer,
				form,
				submitForm,
				ruleRefForm,
				handlePictureCardPreview,
				handleRemove,
				backageImagesOnSuccess,
				uploadBanner,
				openShowClass,
				onArticleClassSubmit,
				emitClass,
				handleCloseTags,
				handleInputConfirm,
				showInput,
				selectShopList,
				selectShopSubmit,
				delSpu,
				// InputRef,
				...toRefs(state),
				close
			}
		}
	}
</script>

<style lang="scss">
	.page-container {
		margin-top: 10px;
	}

	.customer-detail-drawer {
		overflow: unset;
		position: fixed;
	}

	.customer-modal {
		//left: unset;
	}

	.action-popper {
		background: transparent !important;
		position: relative;

		&:after {
			content: "";
			position: absolute;
			top: 0;
			left: 0;
			right: 0;
			bottom: 0;
			background: var(--el-color-primary-light-9);
			opacity: .8;
			filter: grayscale(100%);
		}

		.el-popper__arrow::before {
			background: var(--el-color-primary-light-9) !important;
			opacity: .8;
			filter: grayscale(100%);
		}

		.sale-title {
			color: var(--el-text-color-primary);
		}
	}

	.tabs-list {
		position: absolute;
		top: 90px;
		left: -50px;
		display: flex;
		flex-direction: column;
		align-items: flex-end;
		overflow: auto;
		max-height: 100%;

		// .tabs-cell{
		//     background: var(--next-color-white);
		//     margin-bottom: 3px;
		//     min-width: 60px;
		//     text-align: right;
		//     padding: 0 5px;
		//     cursor: pointer;
		//     font-size: 12px;
		//     border-radius: 5px 0 0 5px;
		//     box-shadow: rgba(0, 0, 0, 0.15) -1.95px -1.95px 2.6px;
		//     color: var(--el-text-color-secondary);
		//     transition: .1s;
		//     min-height: 35px;
		//     display: flex;
		//     flex-direction: column;
		//     align-items: center;
		//     justify-content: center;
		//     filter: brightness(.85);
		// }
		// .tabs-cell:hover,
		// .active{
		//     background: var(--el-color-primary-dark-2);
		//     color: var(--el-color-primary-light-9);
		//     padding: 5px 8px;
		//     min-width: 70px;
		//     font-size: 14px;
		//     font-weight: bold;
		//     filter: brightness(1)
		// }
		.close-btn {
			width: 50px;
			display: flex;
			align-items: center;
			justify-content: center;
			cursor: pointer;
			background: var(--el-color-primary);
			padding: 5px 0;
			border-radius: 5px 0 0 5px;
		}
	}

	.company-title {
		text-align: center;
		font-size: 18px;
		color: var(--next-bg-menuBar-light-1);
		margin-bottom: 50px;
	}

	.app-container {
		// margin-top: 3px;
		background: #f9f9f9;
		min-height: calc(100vh - 95px);

		.question_header {
			background: #fff;
			padding: 20px;
			margin: 0 auto 10px;
			max-width: 1200px;
			border-radius: 16px;
			box-shadow: 0 2px 12px 0 rgb(0 0 0 / 10%);
			position: sticky;
			top: 0;
			z-index: 10;
		}

		.answer_page {
			display: flex;
			align-items: flex-start;
			max-width: 1200px;
			margin: 0 auto;

			.title_box {
				//display: flex;
				align-items: flex-start;

				.answer_num {
					//width: 40px;
					font-weight: bold;
					font-size: 16px;
				}

				.answer_question {
					//flex: 1;
					overflow: hidden;
				}
			}

			.answer_card {
				flex: 1;
				overflow: hidden;
				margin-right: 10px;

				.answer_content_box {
					margin: 20px 0 20px 40px;
					border-bottom: 1px solid #eee;
				}
			}

			.question_card {
				width: 280px;
				position: sticky;
				top: 130px;

				.question_num_content {
					display: flex;
					align-items: center;
					flex-wrap: wrap;

					.question_num {
						width: 35px;
						height: 35px;
						margin: 0 15px 12px 0;
						border-radius: 8px;
						border: 1px solid #eee;
						cursor: pointer;
						font-size: 14px;
						display: flex;
						align-items: center;
						justify-content: center;
					}

					.question_num:hover {
						background: #409EFF;
						color: #fff;
						border-color: #409EFF;
					}

					.question_num:nth-child(5n+5) {
						margin-right: 0;
					}

					.success {
						background: rgba(#67C23A, .1);
						border-color: #67C23A;
						color: #67C23A;
					}

					.error {
						background: rgba(#F56C6C, .1);
						border-color: #F56C6C;
						color: #F56C6C;
					}
				}
			}

			.fixed_answer_icon {
				display: none;
			}

			@media screen and(max-width: 750px) {
				.answer_card {
					margin-right: 0;
				}

				.question_card {
					position: fixed;
					z-index: 99;
					top: unset;
					bottom: -100vh;
					width: 90%;

					.question_num_content {
						.question_num {
							margin-right: 12px;
						}

						.question_num:nth-child(5n+5) {
							margin-right: 12px;
						}
					}
				}

				.question_fixed_active {
					top: unset;
					bottom: 0;
					transition: .2s;
				}

				.fixed_answer_icon {
					display: block;
					position: fixed;
					width: 48px;
					height: 48px;
					background: #409EFF;
					z-index: 99;
					top: 40%;
					right: 0;
					border-radius: 8px 0 0 8px;
					display: flex;
					align-items: center;
					justify-content: center;

					i {
						font-size: 24px;
						color: #fff;
					}
				}
			}
		}
	}

	:deep(.el-image__error) {
		font-size: 12px;
	}

	.choice-row {
		margin: 3px 0;
		padding: 9px 15px;
		background: rgb(247, 248, 249);
	}

	.green-row {
		background-color: rgba(103, 194, 58, 0.5);
	}

	.red-row {
		background-color: rgba(245, 108, 108, 0.5);
	}

	// 答题卡小圆点
	.dot {
		display: inline-block;
		width: 6px;
		height: 6px;
		border-radius: 50%;
	}

	.title_label {
		height: 40px;
		line-height: 40px;
	}

	.htmlPage {
        :deep(img) {
			width: 100% !important;
			height: 200px !important;
			object-fit: contain;
		}
	}

	.el-drawer__footer {
		height: 45px;
		padding-right: 35px;
	}
</style>
